package httpserver

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
	"xr-game-server/core/cfg"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/shutdown"
)

const (
	Res             = "/res"
	Ws              = "/ws"
	Token           = "xrtoken"
	AuthId          = "authId"
	DoTime          = "1ea75a33e32449c67dfd40fe8e23232d-doTime"
	LongDoTime      = 400
	contentTypeJson = "application/json"
	JsonUrl         = "/f9acdb1da4ed11ecc115d613e291af14.json"
)

var httpServer = g.Server()

// InitHttpServer 初始化http服务器
func InitHttpServer() {
	//添加静态路径
	httpServer.AddStaticPath(Res, cfg.GetServerCfg().StaticResPath)
	httpServer.EnablePProf()
	//添加端口

	if cfg.GetServerCfg().CertFile != "" {
		httpServer.EnableHTTPS(cfg.GetServerCfg().CertFile, cfg.GetServerCfg().KeyFile)
		glog.Warning(gctx.New(), "启用https 证书")
		httpServer.SetHTTPSPort(443)
	} else {
		if cfg.GetServerCfg().HttpPort == common.Zero {
			cfg.GetServerCfg().HttpPort = 8898
		}
		httpServer.SetPort(cfg.GetServerCfg().HttpPort)
	}
	httpServer.Use(middlewareCORS)
	httpServer.SetOpenApiPath(JsonUrl)
	shutdown.RegCommonShutDownHandler(closeServer)
	httpServer.Run()
}

func GetAuthId(ctx context.Context) uint64 {
	authId := g.RequestFromCtx(ctx).GetHeader(AuthId)
	return gconv.Uint64(authId)
}
